package com.example.home.fragment


import androidx.fragment.app.activityViewModels
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.common.mvvm.BaseMvvmFragment
import com.example.entity.BaseEntity
import com.example.home.R
import com.example.home.adapter.DailyListAdapter
import com.example.home.databinding.FragmentDailyBinding
import com.example.home.uistate.HomeUiState
import com.example.home.viewmodel.HomeViewModel
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.scwang.smart.refresh.header.ClassicsHeader
import dagger.hilt.android.AndroidEntryPoint

@AndroidEntryPoint
class DailyFragment : BaseMvvmFragment<FragmentDailyBinding>() {

    private val mViewModel : HomeViewModel by activityViewModels()
    private  var dailyListAdapter: DailyListAdapter ? = null
    private var isRefresh = false

    companion object {
        @JvmStatic
        fun newInstance() = DailyFragment()
    }
    override fun getLayoutId(): Int=R.layout.fragment_daily

    override fun initViews() {
        mDataBinding.rvDailyView.setHasFixedSize(true)
        mDataBinding.rvDailyView.layoutManager=LinearLayoutManager(requireContext(),RecyclerView.VERTICAL,false)

        dailyListAdapter= DailyListAdapter()
        mDataBinding.rvDailyView.adapter=dailyListAdapter

        //下拉刷新和加载更多的布局组件
        mDataBinding.refreshLayout.setRefreshHeader(ClassicsHeader(requireContext()))
        mDataBinding.refreshLayout.setRefreshFooter(ClassicsFooter(requireContext()))

        //添加下拉加载更多事件
        mDataBinding.refreshLayout.setOnRefreshListener {
            isRefresh=false
            mViewModel.loadDailyData(isRefresh)
        }
        mDataBinding.refreshLayout.setOnLoadMoreListener {
            isRefresh=true
            mViewModel.loadDailyData(isRefresh)
        }

    }


    /**
     * 懒加载数据
     * */
    override fun lazyLoadData() {
        if (dailyListAdapter?.data?.size==0){
            mViewModel.loadDailyData()
        }
    }

    override fun setDataObserver() {
        mViewModel.mLiveData.observe(this){
            when(it){
                is HomeUiState.loadDailySuccess->upDataUi(it.data as MutableList<BaseEntity>)
                is HomeUiState.loadDailyrFail->showMsg(it.error)
                else->{}
            }
        }
    }

    private fun upDataUi(data: MutableList<BaseEntity>) {

        if (!isRefresh){
            dailyListAdapter?.setNewInstance(data)
            if (mDataBinding.refreshLayout.isRefreshing){
                mDataBinding.refreshLayout.finishRefresh()
            }
        }else{
            dailyListAdapter?.addData(data)
            if (mDataBinding.refreshLayout.isLoading){
                mDataBinding.refreshLayout.finishLoadMore()
            }
        }

    }


}